package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.enums.LivePlayBackEvenNameEnum;
import com.ruoyi.common.core.utils.Helper;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.BaseLivePlayBackEven;
import com.ruoyi.system.domain.BaseLiveTournament;
import com.ruoyi.system.domain.LiveStreamCode;
import com.ruoyi.system.domain.dto.CreateLiveWatermarkRuleDto;
import com.ruoyi.system.mapper.BaseLivePlayBackEvenMapper;
import com.ruoyi.system.mapper.BaseLiveTournamentMapper;
import com.ruoyi.system.service.IBaseLivePlayBackEvenService;
import com.ruoyi.system.service.IBaseLiveTournamentService;
import com.tencentcloudapi.mps.v20190612.models.*;
import okhttp3.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 比赛直播房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-10
 */
@Service
public class BaseLivePlayBackEvenServiceImpl extends ServiceImpl<BaseLivePlayBackEvenMapper, BaseLivePlayBackEven> implements IBaseLivePlayBackEvenService {

    @Resource
    LoginUserSetUtil loginUserSetUtil;
    @Resource
    private LiveService liveService;
    @Resource
    private IBaseLiveTournamentService iBaseLiveTournamentService;

    @Override
    public void playbackEvent(String name, Long tournamentId, String videoUrl, Integer type) {
        BaseLivePlayBackEven baseLivePlayBackEvenBuilder = BaseLivePlayBackEven.builder().name(name).status(3).tournamentId(tournamentId).type(type).videoUrl(videoUrl).build();
        loginUserSetUtil.populateFields(baseLivePlayBackEvenBuilder, 1);
        this.save(baseLivePlayBackEvenBuilder);
    }

    @Override
    public void saveStrName(String strName, Long tournamentId, Long playId, Long playerLogId,Integer second) {
        if (StringUtils.isEmpty(strName)) {
            return;
        }
        BaseLiveTournament one = iBaseLiveTournamentService.getOne(Wrappers.<BaseLiveTournament>lambdaQuery()
//                .eq(BaseLiveTournament::getState,1)

                .eq(BaseLiveTournament::getTournamentId, tournamentId)
                .orderByDesc(BaseLiveTournament::getCreateTime)
                .last("limit 1"));
        if (Objects.isNull(one)) {
            return;
        }
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime beginTime = endTime.minusSeconds(second);
        List<BaseLivePlayBackEven> list = list(Wrappers.<BaseLivePlayBackEven>lambdaQuery().eq(BaseLivePlayBackEven::getPlayerLogId, playerLogId));
        if (CollUtil.isNotEmpty(list)) {
            return;
        }
        String obsCode = liveService.getHighlightShot(one.getViewUrl(), beginTime, endTime);

        BaseLivePlayBackEven baseLivePlayBackEvenBuilder = BaseLivePlayBackEven.builder()
                .name(strName)
                .playId(playId)
                .playerLogId(playerLogId)
                .tournamentId(tournamentId)
                .videoUrl(obsCode).build();
        loginUserSetUtil.populateFields(baseLivePlayBackEvenBuilder, 1);
        this.save(baseLivePlayBackEvenBuilder);

//        eventLiveService(baseLivePlayBackEvenBuilder);
    }

    @Async
    public void eventLiveService(BaseLivePlayBackEven vo) {
        ProcessMediaResponse responseProcessMedia = liveService.ProcessMedia(vo.getVideoUrl());
        if (Objects.nonNull(responseProcessMedia) && Objects.nonNull(responseProcessMedia.getTaskId())) {
            vo.setTaskId(responseProcessMedia.getTaskId());
            vo.setStatus(1);
            DescribeTaskDetailResponse response = liveService.DescribeTaskDetail(vo.getTaskId());
            if (Objects.nonNull(response)) {
                if (response.getTaskType().equals("EditMediaTask")) {
                    EditMediaTask editMediaTask = response.getEditMediaTask();
                    if (Objects.nonNull(editMediaTask)) {
                        EditMediaTaskOutput output = editMediaTask.getOutput();
                        if (Objects.nonNull(output)) {
                            if (vo.getName().equals(LivePlayBackEvenNameEnum.PERSONAL_HIGHLIGHTS.getName())) {
                                String url = StringUtils.isNoneBlank(output.getPath()) ? output.getPath() : "/file/all_EditMedia_" + vo.getTournamentId().toString() + vo.getPlayId().toString() + ".mp4";
                                vo.setVideoUrl("https://ydsg-1256672631.cos.ap-guangzhou.myqcloud.com" + url);
                            } else {
                                String url = StringUtils.isNoneBlank(output.getPath()) ? output.getPath() : "/file/all_EditMedia_" + vo.getTournamentId() + ".mp4";
                                vo.setVideoUrl("https://ydsg-1256672631.cos.ap-guangzhou.myqcloud.com" + url);
                            }
                            vo.setStatus(3);
                        }
                    }
                } else {
                    ScheduleTask scheduleTask = response.getScheduleTask();
                    if (Objects.nonNull(scheduleTask)) {
                        ActivityResult[] activityResultSet = scheduleTask.getActivityResultSet();
                        ActivityResult activityResult = activityResultSet[0];
                        if (Objects.nonNull(activityResult)) {
                            ActivityResItem activityResItem = activityResult.getActivityResItem();
                            if (Objects.nonNull(activityResItem)) {
                                MediaProcessTaskTranscodeResult transcodeTask = activityResItem.getTranscodeTask();
                                if (Objects.nonNull(transcodeTask)) {
                                    MediaTranscodeItem output = transcodeTask.getOutput();
                                    if (Objects.nonNull(output)) {
                                        String url = StringUtils.isNoneBlank(output.getPath()) ? output.getPath() : "/file/all_EditMedia_" + vo.getTournamentId() + ".mp4";
                                        vo.setVideoUrl("https://ydsg-1256672631.cos.ap-guangzhou.myqcloud.com" + url);
                                        if (Objects.equals(vo.getName(), "二分命中") || Objects.equals(vo.getName(), "三分命中")
                                                || Objects.equals(vo.getName(), "一分命中") || Objects.equals(vo.getName(), "罚球命中")) {
                                            vo.setStatus(2);
                                        } else {
                                            vo.setStatus(3);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            this.updateById(vo);
        }
    }

    @Override
    public void updatePlayId(Long basketballPlayerId, Long playerLogId) {
        LambdaUpdateWrapper<BaseLivePlayBackEven> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.set(BaseLivePlayBackEven::getPlayId, basketballPlayerId);
        updateWrapper.eq(BaseLivePlayBackEven::getPlayerLogId, playerLogId);
        this.update(updateWrapper);
    }

    @Override
    public void deleteByPlayerLogId(Long id) {
        this.update(Wrappers.<BaseLivePlayBackEven>lambdaUpdate()
                .set(BaseLivePlayBackEven::getIsDeleted, 1)
                .eq(BaseLivePlayBackEven::getPlayerLogId, id));
    }

    @Override
    public void batchRemote(Long tournamentId) {
        List<BaseLivePlayBackEven> list = list(Wrappers.<BaseLivePlayBackEven>lambdaQuery()
                .eq(BaseLivePlayBackEven::getTournamentId, tournamentId)
                .eq(BaseLivePlayBackEven::getIsDeleted, 0)
        );
        List<BaseLivePlayBackEven> newBackEven = new ArrayList<>();
        Map<Long, List<BaseLivePlayBackEven>> playBackLogMap = list.stream().filter(o -> Objects.nonNull(o.getPlayerLogId())).collect(Collectors.groupingBy(BaseLivePlayBackEven::getPlayerLogId));
        playBackLogMap.forEach((key, value) -> {
            if (value.size() > 1) {
                for (int i = 1; i < value.size(); i++) {
                    BaseLivePlayBackEven even = value.get(i);
                    even.setIsDeleted(1L);
                    newBackEven.add(even);
                }
            }
        });
        updateBatchById(newBackEven);
    }

    @Override
    public void timeCut(BaseLivePlayBackEven baseLiveTournament) {
        BaseLiveTournament one = iBaseLiveTournamentService.getOne(Wrappers.<BaseLiveTournament>lambdaQuery()
                .eq(BaseLiveTournament::getState, 1)
                .eq(BaseLiveTournament::getTournamentId, baseLiveTournament.getTournamentId())
                .last("limit 1"));
        if (Objects.isNull(one)) {
            throw new RuntimeException("该比赛未开播");
        }
        // 定义格式化器（HH：24小时制，hh：12小时制）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        // 格式化时间
        String formattedTime = LocalTime.now().format(formatter);
        saveStrName(LivePlayBackEvenNameEnum.INSTANT_CUT.getName() + formattedTime, baseLiveTournament.getTournamentId(), null, null,120);
    }

}
